﻿$(function () {
    $('script[type]').each(function () {
        if ($(this).attr('type') == 'text/x-jquery-tmpl') {
            $(this).html($(this).html().replace(/..\/%7B/g, '{').replace(/%7B/g, '{').replace(/%7D/g, '}'))
        }
    });

    var $opinions = $('#pnlSimilarOpinions');
    var $opinionsLoad = $('#opinionsLoad');
    var $trigger = $('#opinions-load-trigger');
    var opinionId = $('#opinionId').val();

    $opinionsLoad.hide();
    $trigger.waypoint(function (e, d) {
        $opinionsLoad.show();
        $trigger.waypoint('remove');
        LoadSimilarOpinions(opinionId, $opinions, function (haveElements) {
            $opinionsLoad.hide();
            if (haveElements)
                $trigger.waypoint({ offset: '100%' });

        });
    }, { offset: '100%' });

});

function LoadSimilarOpinions(opinionId, container, callbackAfterLoad) {
    var lastId = 0;
    if ($('div[id^=opinion-item-]').length > 0)
        lastId = parseInt($('div[id^=opinion-item-]:last').attr('id').replace('opinion-item-', ''));
    $.ajax({
        type: "POST",
        url: "/Handlers/BlackApartService.asmx/GetSimilarOpinions",
        data: "{lastLoadedOpinion:" + lastId + ", opinionId:" + opinionId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var haveElements = msg['d'].length > 0;
            if (haveElements)
                $('#opinion-item').tmpl(msg['d']).appendTo(container);
            if (callbackAfterLoad) {
                callbackAfterLoad(haveElements);
            }
        }
    });
}